package database;

import database.employee.tb_employee;
import redis.clients.jedis.Jedis;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import database.CallMySQLStoredProcedure;

import static database.CallMySQLStoredProcedure.getElevel;

public class GUI {//用户登录界面
    public static void main(String[] args) {
        tb_employee e1=new tb_employee();
        SwingUtilities.invokeLater(() -> GUI(e1));
    }

    public static void GUI(tb_employee e1) {
        //照片添加
        //ImageIcon icon = new ImageIcon("C:\\Users\\21568\\Pictures\\Screenshots\\超市.png");
        //ImagePanel imagePanel = new ImagePanel(new ImageIcon("C:\\Users\\21568\\Pictures\\Screenshots\\超市.jpg").getImage());

        // 加载图片文件到 ImageIcon
        ImageIcon icon = new ImageIcon("C:\\Users\\21568\\Pictures\\Screenshots\\超市头标.png");

        // 获取 Image 对象
        Image image = icon.getImage();

        JFrame frame = new JFrame("超市用户登录界面");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 设置窗口图标
        frame.setIconImage(image);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        //窗口大小设置
        frame.setBounds(100,100,400,300);
        frame.setResizable(false);


        //照片添加
        //ImageIcon icon = new ImageIcon("C:\\Users\\21568\\Pictures\\Screenshots\\钥匙.png");
        //添加界面背景图
        ImagePanel imagePanel = new ImagePanel(new ImageIcon("C:\\Users\\杨\\Desktop\\壁纸\\登录背景.jpg").getImage());
        frame.setContentPane(imagePanel);

        //其他
        ImageIcon originalIcon1 = new ImageIcon("C:\\Users\\杨\\Desktop\\壁纸\\锁2.jpg");
        Image scaledImage1 = originalIcon1.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH); // 调整图标大小
        ImageIcon scaledIcon1 = new ImageIcon(scaledImage1);

        ImageIcon originalIcon2 = new ImageIcon("C:\\Users\\杨\\Desktop\\壁纸\\钥匙.jpg");
        Image scaledImage2 = originalIcon2.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH); // 调整图标大小
        ImageIcon scaledIcon2 = new ImageIcon(scaledImage2);


        // 账号密码的声明
        JLabel label = new JLabel("账号:");
        label.setIcon(scaledIcon1);
        label.setHorizontalTextPosition(SwingConstants.RIGHT); // 设置文本相对于图标的位置
        JLabel label2 = new JLabel("密码:");
        label2.setIcon(scaledIcon2);
        label2.setHorizontalTextPosition(SwingConstants.RIGHT); // 设置文本相对于图标的位置
        JTextField JF1 = new JTextField(10);
        JPasswordField JF2 = new JPasswordField(10); // 使用JPasswordField以隐藏密码

        ImageIcon originalIcon = new ImageIcon("C:\\Users\\杨\\Desktop\\壁纸\\锁.jpg");
        Image scaledImage = originalIcon.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH); // 调整图标大小
        ImageIcon scaledIcon = new ImageIcon(scaledImage);

        // 添加登录按键
        JButton jb1 = new JButton("登录");
        jb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取文本框内容
                String Account = JF1.getText();
                String Password = new String(JF2.getPassword());

                // 检查账号和密码是否为空
                if (Account.isEmpty() || Password.isEmpty()) {
                    JOptionPane.showMessageDialog(frame, "账号或密码不能为空！", "登录提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                String key = Account; // 使用账号作为键
                String storedPassword = null;
                try (Jedis jedis = new Jedis("localhost", 6379)) {
                    String storedValue = jedis.get(key);
                    if (storedValue != null) {
                        String[] parts = storedValue.split(",");
                        if (parts.length > 2) {
                            storedPassword = parts[2];
                            // 验证账号和密码
                            if (storedPassword != null && storedPassword.equals(Password)) {
                                // 登录成功逻辑
                            } else {
                                JOptionPane.showMessageDialog(frame, "账号或密码错误！", "登录提示", JOptionPane.WARNING_MESSAGE);
                            }
                        } else {
                            JOptionPane.showMessageDialog(frame, "Stored value does not contain enough parts.", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(frame, "No value found for the given key in Redis.", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception ex) {
                    // 处理Redis连接失败或其他异常
                    JOptionPane.showMessageDialog(frame, "登录失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
                // 验证账号和密码
                if (storedPassword.equals(Password)) {
                    int eLevel = getElevel(Account);
                    e1.authenticate(e1,Account,Password);
                    // 判断级别
                    if (eLevel == 00) {
                        new GUImanager(e1);
                        frame.dispose();
                    } else if (eLevel == 20) {
                        new GUIemployee(e1);
                        frame.dispose();
                    } else if (eLevel == 10) {
                        new GUImanager(e1);
                        frame.dispose();
                    } else {
                        JOptionPane.showMessageDialog(frame, "账号或密码错误！", "登录提示", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }

            });

        // 使用面板来控制标签和文本框的对齐
        JPanel inputPanel1 = new JPanel(new FlowLayout());
        inputPanel1.add(label);
        inputPanel1.add(JF1);

        panel.add(inputPanel1);
        panel.add(Box.createVerticalStrut(10)); // 添加垂直间距

        JPanel inputPanel2 = new JPanel(new FlowLayout());
        inputPanel2.add(label2);
        inputPanel2.add(JF2);

        panel.add(inputPanel2);
        panel.add(Box.createVerticalStrut(10)); // 再次添加垂直间距

        panel.add(jb1, BorderLayout.SOUTH); // 注意这里应该使用BorderLayout.CENTER

        frame.add(panel);
        frame.setLocationRelativeTo(null); // 居中显示
        frame.setVisible(true);
    }


    static class ImagePanel extends JPanel {
        private Image backgroundImage;

        // 构造方法，接受图像作为参数
        public ImagePanel(Image image) {
            this.backgroundImage = image;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // 绘制背景图片
            g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
        }
    }
    private static int getEmployeeLevel(String accountId) {
        int employeeLevel = -1; // 默认值，表示没有找到级别或发生错误
        String selectSql = "SELECT Elevel FROM tb_employee WHERE Eid = ?";
        try (Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "123456");
             PreparedStatement pstmt = conn.prepareStatement(selectSql)) {

            pstmt.setString(1, accountId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    // 从结果集中获取员工级别
                    employeeLevel = rs.getInt("Elevel");
                }
            }
        } catch (SQLException ex) {
            // 日志记录异常信息
            System.err.println("数据库查询失败: " + ex.getMessage());
            ex.printStackTrace();
        }
        return employeeLevel;
    }

}
